package com.tf.six.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.tf.six.entity.User;
import com.tf.six.service.UserCollectionService;
import com.tf.six.service.UserService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.responses.ApiResponse;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.http.ResponseEntity;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Slf4j
@RestController
@RequestMapping("/api/users")
@Tag(name = "用户接口", description = "符合Restful风格的用户接口")
public class UserController {
    @Autowired
    private UserService userService;
    @Autowired
    private UserCollectionService userCollectionService;
    @Autowired
    private AuthenticationManager authenticationManager;

    // 用户注册
    @Operation(summary = "用户注册", description = "用户注册")
    @PostMapping("/register")
    @ApiResponse(responseCode = "200", description = "注册成功")
    public ResponseEntity<Map<String, Object>> register(@RequestBody User user) {
        Map<String, Object> result = new HashMap<>();
        boolean success = userService.registerUser(user);

        if (success) {
            result.put("code", 200);
            result.put("message", "注册成功");
            return ResponseEntity.ok(result);
        } else {
            result.put("code", 500);
            result.put("message", "注册失败");
            return ResponseEntity.status(500).body(result);
        }
    }

    // 用户登录，使用 Spring Security 认证
    @Operation(summary = "用户登录", description = "用户登录")
    @PostMapping("/login")
    @ApiResponse(responseCode = "200", description = "登录成功")
    public ResponseEntity<Map<String, Object>> login(@RequestParam String username, @RequestParam String password) {
        Map<String, Object> result = new HashMap<>();

        try {
            // 进行认证
            Authentication authentication = authenticationManager.authenticate(
                    new UsernamePasswordAuthenticationToken(username, password)
            );

            // 将认证信息存储到 SecurityContext
            SecurityContextHolder.getContext().setAuthentication(authentication);

            // 登录成功，返回用户信息和 token（简化示例，实际项目中应生成 JWT Token）
            User user = userService.lambdaQuery().eq(User::getUsername, username).one();

            result.put("code", 200);
            result.put("message", "登录成功");
            result.put("user", user);
            // 在实际项目中，这里应该返回 JWT Token
            return ResponseEntity.ok(result);
        } catch (Exception e) {
            result.put("code", 401);
            result.put("message", "认证失败：" + e.getMessage());
            return ResponseEntity.status(401).body(result);
        }
    }


    // 查询所有用户
    @Operation(summary = "查询所有用户", description = "查询所有用户")
    @GetMapping
    @ApiResponse(responseCode = "200", description = "查询所有用户返回用户list")
    public List<User> getAllUsers() {
        return userService.list();
    }

    // 查询单个用户，根据id
    @Cacheable(value = "dataCache", key = "#id")
    @GetMapping("/{id}")
    public User getUserById(@PathVariable("id") Integer id) {
        log.error("id: {}", id);
        return userService.getById(id);
    }

    // 分页查询
    @GetMapping("/querypage/{page}/{size}")
    public List<User> queryPage(@PathVariable("page") Integer page, @PathVariable("size") Integer size) {
        Page<User> testpage = new Page<>(page, size);
        Page<User> userPage = userService.page(testpage, null);
        return userPage.getRecords();
    }

    // 进行多条件分页查询
    @GetMapping("/querylist/{page}/{size}")
    public List<User> queryList(@PathVariable("page") Integer page,
                                @PathVariable("size") Integer size,
                                @RequestBody User user) {
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        if (user.getUsername() != null) {
            queryWrapper.like("username", user.getUsername());
        }
        if (user.getEmail() != null) {
            queryWrapper.like("email", user.getEmail());
        }
        Page<User> testpage = new Page<>(page, size);
        Page<User> userPage = userService.page(testpage, queryWrapper);
        return userPage.getRecords();
    }

    // 添加用户
    @PostMapping
    public boolean addUser(@RequestBody User user) {
        return userService.save(user);
    }

    // 修改用户
    @CachePut(value = "dataCache", key = "#user.id")
    @PutMapping
    public boolean updateUser(@RequestBody User user) {
        return userService.updateById(user);
    }

    // 删除用户
    @CacheEvict(value = "dataCache", key = "#id")
    @DeleteMapping("/{id}")
    public boolean deleteUser(@PathVariable("id") Integer id) {
        return userService.removeById(id);
    }

    // 添加收藏
    @PostMapping("/{userId}/collection/{itemId}")
    public boolean addCollection(@PathVariable("userId") Integer userId, @PathVariable("itemId") Integer itemId) {
        return userCollectionService.addCollection(userId, itemId);
    }

    // 移除收藏
    @DeleteMapping("/{userId}/collection/{itemId}")
    public boolean removeCollection(@PathVariable("userId") Integer userId, @PathVariable("itemId") Integer itemId) {
        return userCollectionService.removeCollection(userId, itemId);
    }
}
